package com.qiaoya.model.entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;

@Accessors(chain = true)
@NoArgsConstructor
@Getter
@Setter
public class WatchCommandEntity implements Serializable, Cloneable{

	private static final long serialVersionUID = 7698862379923111158L;

	private int ternimalType;
	private int version;
	private String encodeType;
	private String commandCode;
	private String imei;
	private String commandType;
	private ArrayList<String> parameters = null;

	public WatchCommandEntity(String[] command) {
			//>=6
			this.ternimalType = Integer.parseInt(command[0]);
			this.version = Integer.parseInt(command[1]);
			this.encodeType = command[2];
			this.commandCode = command[3];
			this.imei = command[4];
			this.commandType = command[5];
			//parameters split with ","
			if(command.length>6){
				if(command[6]!=null && !command[6].equalsIgnoreCase("")){
					this.parameters = formatString(command[6]);
				}
			}
	}
	
	@Override  
    public WatchCommandEntity clone(){  
		WatchCommandEntity sc = null;  
        try
        {
            sc = (WatchCommandEntity) super.clone();
            ArrayList<String> from = sc.getParameters();
            if(from!=null){
            	ArrayList<String> to = new ArrayList<String>(from.size());
                for (int i = 0; i < from.size(); i++) {
                	to.add(from.get(i));
                }
                sc.setParameters(to);
            }           
        } catch (CloneNotSupportedException e){
            e.printStackTrace();
        }
        return sc;
    }
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		//sb.append(getClass().getSimpleName());
		sb.append("{");
		sb.append(ternimalType);
		sb.append(":").append(version);
		sb.append(":").append(encodeType);
		sb.append(":").append(commandCode);
		sb.append(":").append(imei);
		sb.append(":").append(commandType);
		if(parameters!=null){
			sb.append(":").append(formatList(parameters));
		}
		sb.append("}").append("\r\n");
		return sb.toString();
	}

	public String formatList(ArrayList<String> list) {
		StringBuilder b = new StringBuilder();
		for (String o : list) {
			if (list.size() > list.indexOf(o) + 1)
				b.append(o).append(",");
			else {
				b.append(o);
			}
		}
		return b.toString();
	}
	
	public ArrayList<String> formatString(String paramters) {
		String[] commands =  paramters.split(",");
		return new ArrayList<String>(Arrays.asList(commands));
	}
}
